package com.netty.im.service;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * Created by Administrator on 2018/9/9/009.
 */
public class ImServiceHandler extends SimpleChannelInboundHandler<String> {
    private static ChannelGroup channelGroop = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();

        channelGroop.forEach(ch -> {
            if (channel != ch) {
                ch.writeAndFlush(channel.remoteAddress() + " 发送的消息:" + msg + "\n");
            } else {
                ch.writeAndFlush("【自己】:" + msg + "\n");
            }
        });
    }

    /**
     * 客户端链接建立好链接之后回调此方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("ChannelHandlerContext:" + channel.remoteAddress() + " 上线");
        //广播Group里面的所有所有channel
        channelGroop.writeAndFlush("【服务器】- " + channel.remoteAddress() + " 加入\n");
        channelGroop.add(channel);

    }

    /**
     * 连接关闭
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        channelGroop.writeAndFlush("【服务器】- " + ctx.channel().remoteAddress() + " 离开\n");
    }

    /**
     * 连接活跃状态
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + " 上线");
        channel.writeAndFlush(channel.remoteAddress() + " 上线\r\n");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + " 下线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
